package com.lanvideo.controller;

import com.lanvideo.entity.User;
import com.lanvideo.service.UserService;
import com.lanvideo.service.SessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private SessionService sessionService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> loginData, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        String username = loginData.get("username");
        String password = loginData.get("password");
        
        // 先检查用户是否存在
        User user = userService.getUserByUsername(username);
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
            return ResponseEntity.ok(result);
        }
        
        // 检查用户状态
        if (user.getStatus() == null || user.getStatus() == 0) {
            result.put("success", false);
            result.put("message", "账户已被禁用，请联系管理员");
            return ResponseEntity.ok(result);
        }
        
        // 验证密码
        if (userService.verifyPassword(password, user.getPassword())) {
            // 登录成功，将用户信息存入session
            session.setAttribute("user", user);
            session.setAttribute("userId", user.getId());
            session.setAttribute("userRole", user.getRole());
            
            // 使用会话管理服务
            sessionService.onUserLogin(user, session);
            
            // 更新最后登录时间
            userService.updateLastLoginTime(user.getId());
            
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("user", user);
            result.put("onlineCount", sessionService.getOnlineUserCount());
        } else {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        
        // 验证角色（只允许注册老师和学生）
        if (user.getRole() == null || (user.getRole() != 1 && user.getRole() != 2)) {
            result.put("success", false);
            result.put("message", "只能注册老师或学生账户");
            return ResponseEntity.ok(result);
        }
        
        boolean success = userService.register(user);
        if (success) {
            result.put("success", true);
            result.put("message", "注册成功");
        } else {
            result.put("success", false);
            result.put("message", "用户名已存在");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 使用会话管理服务
        sessionService.onUserLogout(session);
        
        session.invalidate();
        result.put("success", true);
        result.put("message", "登出成功");
        result.put("onlineCount", sessionService.getOnlineUserCount());
        return ResponseEntity.ok(result);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/current")
    public ResponseEntity<Map<String, Object>> getCurrentUser(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute("user");
        
        if (user != null) {
            result.put("success", true);
            result.put("user", user);
        } else {
            result.put("success", false);
            result.put("message", "用户未登录");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/update")
    public ResponseEntity<Map<String, Object>> updateUser(@RequestBody User user, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            return ResponseEntity.ok(result);
        }
        
        // 设置用户ID
        user.setId(currentUser.getId());
        
        boolean success = userService.updateUser(user);
        if (success) {
            // 更新session中的用户信息
            User updatedUser = userService.getUserById(currentUser.getId());
            session.setAttribute("user", updatedUser);
            
            result.put("success", true);
            result.put("message", "更新成功");
            result.put("user", updatedUser);
        } else {
            result.put("success", false);
            result.put("message", "更新失败");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取所有用户（管理员功能）
     */
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllUsers(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null || userRole != 0) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.ok(result);
        }
        
        List<User> users = userService.getAllUsers();
        result.put("success", true);
        result.put("users", users);
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取在线用户统计
     */
    @GetMapping("/online-stats")
    public ResponseEntity<Map<String, Object>> getOnlineStats(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null || userRole != 0) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.ok(result);
        }
        
        result.put("success", true);
        result.put("onlineCount", sessionService.getOnlineUserCount());
        result.put("timestamp", System.currentTimeMillis());
        
        return ResponseEntity.ok(result);
    }

    /**
     * 强制用户下线（管理员功能）
     */
    @PostMapping("/force-logout/{userId}")
    public ResponseEntity<Map<String, Object>> forceLogout(@PathVariable Integer userId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null || userRole != 0) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.ok(result);
        }
        
        boolean success = sessionService.forceUserLogout(userId);
        if (success) {
            result.put("success", true);
            result.put("message", "用户已强制下线");
        } else {
            result.put("success", false);
            result.put("message", "用户不在线或下线失败");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员获取所有用户列表
     */
    @GetMapping("/admin/list")
    public ResponseEntity<Map<String, Object>> getAdminUserList(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以查看用户列表");
                return ResponseEntity.ok(result);
            }
            
            List<User> users = userService.getAllUsers();
            result.put("success", true);
            result.put("users", users);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员创建用户
     */
    @PostMapping("/admin/create")
    public ResponseEntity<Map<String, Object>> createUserByAdmin(@RequestBody User user, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以创建用户");
                return ResponseEntity.ok(result);
            }
            
            if (userService.createUser(user)) {
                result.put("success", true);
                result.put("message", "用户创建成功");
            } else {
                result.put("success", false);
                result.put("message", "用户创建失败，用户名或邮箱已存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员更新用户
     */
    @PutMapping("/admin/update/{userId}")
    public ResponseEntity<Map<String, Object>> updateUserByAdmin(@PathVariable Integer userId, 
                                                               @RequestBody User user, 
                                                               HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以更新用户");
                return ResponseEntity.ok(result);
            }
            
            // 获取现有用户信息
            User existingUser = userService.getUserById(userId);
            if (existingUser == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return ResponseEntity.ok(result);
            }
            
            // 调试：显示现有用户信息
            System.out.println("=== Existing User Info ===");
            System.out.println("Existing User ID: " + existingUser.getId());
            System.out.println("Existing Username: " + existingUser.getUsername());
            System.out.println("Existing Name: " + existingUser.getName());
            System.out.println("Existing Email: " + existingUser.getEmail());
            System.out.println("Existing Phone: " + existingUser.getPhone());
            System.out.println("Existing Role: " + existingUser.getRole());
            System.out.println("=== End Existing User Info ===");
            
            // 更新允许的字段
            existingUser.setUsername(user.getUsername());
            existingUser.setName(user.getName());
            existingUser.setEmail(user.getEmail());
            existingUser.setPhone(user.getPhone());
            existingUser.setRole(user.getRole());
            
            // 如果提供了新密码，则更新密码（需要加密）
            if (user.getPassword() != null && !user.getPassword().trim().isEmpty()) {
                existingUser.setPassword(userService.hashPassword(user.getPassword()));
                System.out.println("Password will be updated and encrypted");
            } else {
                System.out.println("Password will not be updated (empty or null)");
            }
            
            // 调试日志
            System.out.println("=== UserController.updateUserByAdmin Debug ===");
            System.out.println("Admin ID: " + adminId);
            System.out.println("Target User ID: " + userId);
            System.out.println("Updated Username: " + existingUser.getUsername());
            System.out.println("Updated Name: " + existingUser.getName());
            System.out.println("Updated Email: " + existingUser.getEmail());
            System.out.println("Updated Phone: " + existingUser.getPhone());
            System.out.println("Updated Role: " + existingUser.getRole());
            System.out.println("=== End Debug ===");
            
            if (userService.updateUserInfo(existingUser)) {
                result.put("success", true);
                result.put("message", "用户更新成功");
            } else {
                result.put("success", false);
                result.put("message", "用户更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员删除用户
     */
    @DeleteMapping("/admin/delete/{userId}")
    public ResponseEntity<Map<String, Object>> deleteUserByAdmin(@PathVariable Integer userId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以删除用户");
                return ResponseEntity.ok(result);
            }
            
            // 不能删除自己
            if (adminId.equals(userId)) {
                result.put("success", false);
                result.put("message", "不能删除自己的账号");
                return ResponseEntity.ok(result);
            }
            
            if (userService.deleteUser(userId)) {
                result.put("success", true);
                result.put("message", "用户删除成功");
            } else {
                result.put("success", false);
                result.put("message", "用户删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员重置用户密码
     */
    @PutMapping("/admin/reset-password/{userId}")
    public ResponseEntity<Map<String, Object>> resetUserPassword(@PathVariable Integer userId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以重置密码");
                return ResponseEntity.ok(result);
            }
            
            if (userService.resetPassword(userId, "123456")) {
                result.put("success", true);
                result.put("message", "密码重置成功，新密码为：123456");
            } else {
                result.put("success", false);
                result.put("message", "密码重置失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 更新用户状态（管理员和老师都可以使用）
     */
    @PutMapping("/status/{userId}")
    public ResponseEntity<Map<String, Object>> updateUserStatus(@PathVariable Integer userId, 
                                                               @RequestBody Map<String, Object> requestData, 
                                                               HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer currentUserId = (Integer) session.getAttribute("userId");
            if (currentUserId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User currentUser = userService.getUserById(currentUserId);
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return ResponseEntity.ok(result);
            }
            
            // 检查权限：管理员可以更新所有用户状态，老师可以更新学生状态
            User targetUser = userService.getUserById(userId);
            if (targetUser == null) {
                result.put("success", false);
                result.put("message", "目标用户不存在");
                return ResponseEntity.ok(result);
            }
            
            boolean hasPermission = false;
            if (currentUser.getRole() == 0) { // 管理员
                hasPermission = true;
            } else if (currentUser.getRole() == 1 && targetUser.getRole() == 2) { // 老师更新学生
                hasPermission = true;
            }
            
            if (!hasPermission) {
                result.put("success", false);
                result.put("message", "权限不足");
                return ResponseEntity.ok(result);
            }
            
            Integer newStatus = (Integer) requestData.get("status");
            if (newStatus == null || (newStatus != 0 && newStatus != 1)) {
                result.put("success", false);
                result.put("message", "状态值无效");
                return ResponseEntity.ok(result);
            }
            
            // 直接更新用户状态
            if (userService.updateUserStatus(userId, newStatus)) {
                // 如果用户被禁用，强制退出该用户的所有会话
                if (newStatus == 0) {
                    sessionService.forceUserLogout(userId);
                }
                
                result.put("success", true);
                result.put("message", "用户状态更新成功" + (newStatus == 0 ? "，已强制退出该用户的所有会话" : ""));
            } else {
                result.put("success", false);
                result.put("message", "用户状态更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取用户列表（通用接口，根据角色返回不同数据）
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getUserList(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer currentUserId = (Integer) session.getAttribute("userId");
            if (currentUserId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User currentUser = userService.getUserById(currentUserId);
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return ResponseEntity.ok(result);
            }
            
            List<User> users;
            if (currentUser.getRole() == 0) { // 管理员可以查看所有用户
                users = userService.getAllUsers();
            } else if (currentUser.getRole() == 1) { // 老师可以查看学生
                users = userService.getUsersByRole(2);
            } else { // 学生只能查看自己
                users = java.util.Arrays.asList(currentUser);
            }
            
            result.put("success", true);
            result.put("users", users);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取学生列表（老师和管理员）
     */
    @GetMapping("/students")
    public ResponseEntity<Map<String, Object>> getStudents(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                return ResponseEntity.ok(result);
            }
            
            User currentUser = userService.getUserById(userId);
            if (currentUser.getRole() == 2) { // 学生不能查看学生列表
                result.put("success", false);
                result.put("message", "权限不足");
                return ResponseEntity.ok(result);
            }
            
            List<User> students = userService.getUsersByRole(2); // 获取所有学生
            result.put("success", true);
            result.put("students", students);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取当前用户个人资料
     */
    @GetMapping("/profile")
    public ResponseEntity<Map<String, Object>> getUserProfile(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                return ResponseEntity.ok(result);
            }

            User user = userService.getUserById(userId);
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return ResponseEntity.ok(result);
            }

            // 不返回密码信息
            user.setPassword(null);
            result.put("success", true);
            result.put("user", user);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 更新当前用户个人资料
     */
    @PutMapping("/profile")
    public ResponseEntity<Map<String, Object>> updateUserProfile(@RequestBody Map<String, Object> profileData, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                return ResponseEntity.ok(result);
            }

            User currentUser = userService.getUserById(userId);
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return ResponseEntity.ok(result);
            }

            // 更新允许修改的字段
            if (profileData.containsKey("name")) {
                currentUser.setName((String) profileData.get("name"));
            }
            if (profileData.containsKey("email")) {
                currentUser.setEmail((String) profileData.get("email"));
            }
            if (profileData.containsKey("phone")) {
                currentUser.setPhone((String) profileData.get("phone"));
            }
            if (profileData.containsKey("avatar")) {
                currentUser.setAvatar((String) profileData.get("avatar"));
            }

            // 更新用户信息
            boolean updated = userService.updateUser(currentUser);
            if (updated) {
                result.put("success", true);
                result.put("message", "个人资料更新成功");
                // 返回更新后的用户信息（不包含密码）
                currentUser.setPassword(null);
                result.put("user", currentUser);
            } else {
                result.put("success", false);
                result.put("message", "更新失败，请稍后重试");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 修改密码
     */
    @PutMapping("/change-password")
    public ResponseEntity<Map<String, Object>> changePassword(@RequestBody Map<String, String> passwordData, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                return ResponseEntity.ok(result);
            }

            String oldPassword = passwordData.get("oldPassword");
            String newPassword = passwordData.get("newPassword");
            String confirmPassword = passwordData.get("confirmPassword");

            if (oldPassword == null || newPassword == null || confirmPassword == null) {
                result.put("success", false);
                result.put("message", "请填写完整的密码信息");
                return ResponseEntity.ok(result);
            }

            if (!newPassword.equals(confirmPassword)) {
                result.put("success", false);
                result.put("message", "新密码和确认密码不一致");
                return ResponseEntity.ok(result);
            }

            if (newPassword.length() < 6) {
                result.put("success", false);
                result.put("message", "新密码长度不能少于6位");
                return ResponseEntity.ok(result);
            }

            User currentUser = userService.getUserById(userId);
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return ResponseEntity.ok(result);
            }

            // 验证旧密码
            if (!userService.verifyPassword(oldPassword, currentUser.getPassword())) {
                result.put("success", false);
                result.put("message", "原密码错误");
                return ResponseEntity.ok(result);
            }

            // 更新密码
            currentUser.setPassword(userService.hashPassword(newPassword));
            boolean updated = userService.updateUserPassword(currentUser.getId(), currentUser.getPassword());
            if (updated) {
                result.put("success", true);
                result.put("message", "密码修改成功");
            } else {
                result.put("success", false);
                result.put("message", "密码修改失败，请稍后重试");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
}
